<template>
  <div>
    <el-button type="primary" @click="clickAddProcess">添加过程记录</el-button>
    <el-table :data="data.processTableData" style="width: 100%">
      <el-table-column prop="processId" label="过程ID" width="180"  />
      <el-table-column prop="productId" label="作物ID" width="180" />
      <el-table-column prop="name" label="生长状态" width="180" />
      <el-table-column prop="produceAddress" label="光照情况" width="180" />
      <el-table-column prop="time" label="记录时间" width="180" />
      <el-table-column prop="certification" label="证明材料" width="180" >
        <template #default="scope">
          <el-button type="primary" @click="checkCertification(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="note" label="其他记录" width="180" />

    </el-table>
    <el-dialog  title="新增过程" v-model="data.addProcessVisible">
      <el-form v-model="data.processForm">
        <el-form-item label="过程ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.processId" disabled></el-input>
        </el-form-item>
        <el-form-item label="作物ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="生长状况" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.name" ></el-input>
        </el-form-item>
        <el-form-item label="光照情况" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.produceAddress"></el-input>
        </el-form-item>
        <el-form-item label="记录时间" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.time"></el-input>
        </el-form-item>

        <el-form-item label="其他记录" :label-width="data.formLabelWidth">
          <el-input v-model="data.processForm.note"></el-input>
        </el-form-item>
        <el-form-item label="证明图片" :label-width="data.formLabelWidth">
          <UploadPic @getUploadHash="getHash"/>
        </el-form-item>


      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.processIsVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddProcess">确认</el-button>
          </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.certificationVisible">
      <img class="certification" :src="data.certificationSrc" />
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, reactive} from "vue";
import { useStore } from "vuex";
import { useRoute,useRouter } from "vue-router";
import {v1 as uuidv1} from "uuid";
import {
  func_addProcess,
  func_getAddress, func_getCropById, func_getProductById,
  func_getUserInfo,
  func_getUserProcess,
  func_getUserRole
} from "../../api/etherneum/api";
import UploadPic from "@/components/UploadPic/index";
import ipfsAPI from "ipfs-api";
import {getYMD} from "../../utils/TimeStamp";
import {ElMessage} from "element-plus";
const ipfs = ipfsAPI({ host: "49.234.138.61", port: "5001", protocol: "http" });
export default {
  name: "CropsProcess",
  components:{
    UploadPic
  },
  setup(){
    const store=useStore();
    const route=useRoute();
    const data=reactive({
      cropId:route.params.cropId || store.getters["crops/cropId"],
      tableData:[],
      formLabelWidth:'140px',
      processIsVisible:false,
      processTableData:[],
      processForm:{},
      addProcessVisible:false,

      certificationVisible:false,
      certificationSrc:'',

      cropInfo:{}
    })
    const clickAddProcess=()=>{
      if (data.curUserInfo.role!=1&&(data.curUserInfo.role!=3||data.address!=data.cropInfo.owner)){
        ElMessage.error('无权限')
        return
      }

      data.addProcessVisible=true
      data.processForm.productId=route.params.cropId
      data.processForm.time=getYMD(new Date())
      data.processForm.processId=uuidv1()
    }

    const handleAddProcess=()=>{
      if (!data.processForm.certification){
        ElMessage.error('图片未上传')
        return
      }
      func_addProcess(data.processForm,1)
      data.addProcessVisible=false
    }
    const getAddress = async () => {
      const address = await func_getAddress();
      if (address) {
        store.commit("app/SET_ADDRESS", address);
        let role = await func_getUserRole(address);
        store.commit("app/SET_ROLE", role);
        console.log("getUser address=" + address + " role=" + role);
        data.address = address;
        data.currentRole = role;
        data.curUserInfo = await func_getUserInfo(data.address);
        console.log("cur:" + data.curUserInfo.requestRole);
      }
    };

    const getHash=(hash)=>{
      data.processForm.certification=hash
    }

    const checkCertification=async (row)=>{
      let hash=row.certification
      data.loading=true
      console.log('certification:',row.certification)
      ipfs.get(hash, async (err, result) => {
        console.log('here')
        if (err) throw err;
        let binaryData = [];
        binaryData.push(result[0].content.buffer);
        data.certificationSrc= window.URL.createObjectURL(new Blob(binaryData))
        console.log('src=',data.certificationSrc)
        data.loading=false
      });

      data.certificationVisible=true
    }
    onMounted(()=>{
      getAddress().then(async () => {
        let cropId=route.params.cropId
        console.log('cropId:',cropId)
        data.cropInfo=await func_getCropById(cropId)
        data.processTableData=await func_getUserProcess(cropId,1)
        console.log(data.processTableData)
      });
      ethereum.on("accountsChanged", () => {
        getAddress();
      });
    })
    return{
      data,
      clickAddProcess,
      handleAddProcess,
      getHash,
      checkCertification
    }
  }
}
</script>

<style scoped>

</style>